package cn.itcast.hotel;

import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import java.io.IOException;
import java.util.List;

/**
 * @author guozidi  2023-7-31
 * @Description
 * @package cn.itcast.hotel
 */
public class HotelDay03Demo {


    RestHighLevelClient client = null;

    @BeforeEach
    void before() {
        // 0.初始化Client对象
        client = new RestHighLevelClient(RestClient.builder(
                HttpHost.create("http://192.168.200.100:9200"))
        );
    }

    @AfterEach
    void after() throws IOException {
        // .关闭client
        client.close();
    }


    /**
     * 测试聚合
     */
    @Test
    void testTerms() throws IOException {
        // 1. 创建请求对象
        SearchRequest request = new SearchRequest("hotel");
        // 2. 组装DSL参数
        // 2.1 限定文档数量
        request.source().size(0);
        // 2.2 聚合
        request.source().aggregation(
                AggregationBuilders.terms("brand_agg")
                .field("brand")
                .size(10)
        );
        // 3. 发起请求
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        // 4. 解析结果
        // 4.1 获取聚合结果
        Aggregations aggregations = response.getAggregations();
        // 4.2 根据名称获取具体聚合结果
        Terms brandTerms = aggregations.get("brand_agg");
        // 4.3 获取桶的集合
        List<? extends Terms.Bucket> buckets = brandTerms.getBuckets();
        // 4.4 遍历
        for (Terms.Bucket bucket : buckets) {
            // 获取Key
            String brandName = bucket.getKeyAsString();
            System.out.println(brandName);
        }
    }

}
